import functools
from flask import session, current_app, abort, g
from ihome.models import User


# 获取用户信息装饰器
from ihome.utils.constants import ACCESS_KEY, SECRET_KEY, BUCKET_NAME


def get_user_info(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        user_id = session.get('user_id')
        user = None
        if user_id:
            try:
                user = User.query.get(user_id)
            except BaseException as e:
                current_app.logger.error(e)
                return abort(500)
        g.user = user
        return f(*args, **kwargs)

    return wrapper


# 上传封装
def upload(data):
    import qiniu
    access_key = ACCESS_KEY
    secret_key = SECRET_KEY
    bucket_name = BUCKET_NAME
    q = qiniu.Auth(access_key, secret_key)
    key = None

    token = q.upload_token(bucket_name)
    ret, info = qiniu.put_data(token, key, data)
    if ret is not None:
        return ret.get('key')  # 返回文件名
    else:
        # print(info)  # error message in info
        raise BaseException(info)

